package com.css.springboottest.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.springboottest.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class GltfRead {
//    public final String[] gltfDir={"A5-1","A5-9.10","A5-11.12.13.14","A5-S1.S2.S3.4.5.6.7"};
    public static void main(String[] args) {
//        读取json文件并转化为json 遍历文件夹
     String res=readJsonFile("json/A5_10—chuanghu.gltf");
     Map jobj = JSON.parseObject(res);
     JSONArray nodesArray= (JSONArray) jobj.get("nodes");
     JSONObject assetObject= (JSONObject) jobj.get("asset");
     JSONArray meshArray= (JSONArray) jobj.get("meshes");
     JSONArray bufferArray=(JSONArray) jobj.get("buffers");
     JSONArray imageArray= (JSONArray) jobj.get("images");
     JSONArray accessorsArray= (JSONArray) jobj.get("accessors");
     JSONArray bufferViewerArray= (JSONArray) jobj.get("bufferViews");

       //没遍历一次，写入文件一次 一条sql记录
        for (int i = 0; i < nodesArray.size(); i++) {
            GltfModel gltfModel=new GltfModel();
            //nodes属性
            JSONObject  nodeJson= (JSONObject) nodesArray.get(i);
            Nodes nodeObject=JSON.parseObject(nodeJson.toJSONString(),Nodes.class);
            nodeObject.setMesh(0);
            List<Nodes>nodesList=new ArrayList<>();
            nodesList.add(nodeObject);
            gltfModel.setNodes(nodesList);
            //asset属性
            Asset asset=JSON.parseObject(assetObject.toJSONString(),Asset.class);
            gltfModel.setAsset(asset);
            //scene属性
            int[]sceneNodes=new int[]{0};
            Scene scene=new Scene(sceneNodes);
            List<Scene>sceneList=new ArrayList<>();
            sceneList.add(scene);
            gltfModel.setScenes(sceneList);
            //meshes属性
            JSONObject meshJson= (JSONObject) meshArray.get(i);
            JSONArray primitivesArray= (JSONArray) meshJson.get("primitives");
            JSONObject primiviteJson= (JSONObject) primitivesArray.get(0);
            Primitive primitive=JSONObject.parseObject(primiviteJson.toJSONString(),Primitive.class);
            primitive.setIndices(0);
            Attributes attributes=new Attributes(1,2,3);
            primitive.setAttributes(attributes);
            String meshesName= (String) meshJson.get("name");
            List<Primitive>primitiveList=new ArrayList<>();
            primitiveList.add(primitive);
            Meshes meshes=new Meshes(meshesName, primitiveList);
            List<Meshes>meshesList=new ArrayList<>();
            meshesList.add(meshes);
            gltfModel.setMeshes(meshesList);
            //accessors属性
            List<Accessors>accessorsList=new ArrayList<>();
            JSONObject accors= (JSONObject) accessorsArray.get(i*4);
            List<Object>accorsMin=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors.get("min")).size(); j++) {
                accorsMin.add(((JSONArray) accors.get("min")).get(j));
            }
            List<Object>accorsMax=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors.get("max")).size(); j++) {
                accorsMax.add(((JSONArray) accors.get("max")).get(j));
            }

            Accessors accessors=new Accessors(0,"SCALAR", (Integer) accors.get("componentType"),(Integer)accors.get("count"), (Integer) accors.get("byteOffset"),accorsMin, accorsMax);

            JSONObject accors1= (JSONObject) accessorsArray.get(i*4+1);
            List<Object>accorsMin1=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors1.get("min")).size(); j++) {
                accorsMin1.add(((JSONArray) accors1.get("min")).get(j));
            }
            List<Object>accorsMax1=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors1.get("max")).size(); j++) {
                accorsMax1.add(((JSONArray) accors1.get("max")).get(j));
            }

            Accessors accessors1=new Accessors(1,"VEC3",(Integer)accors1.get("componentType"),(Integer)accors1.get("count"),(Integer)accors1.get("byteOffset"),accorsMin1,accorsMax1);

            JSONObject accors2= (JSONObject) accessorsArray.get(i*4+2);
            List<Object>accorsMin2=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors2.get("min")).size(); j++) {
                accorsMin2.add(((JSONArray) accors2.get("min")).get(j));
            }
            List<Object>accorsMax2=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors2.get("max")).size(); j++) {
                accorsMax2.add(((JSONArray) accors2.get("max")).get(j));
            }

            Accessors accessors2=new Accessors(1,"VEC3",(Integer)accors2.get("componentType"),(Integer)accors2.get("count"),(Integer)accors2.get("byteOffset"),accorsMin2,accorsMax2);

            JSONObject accors3= (JSONObject) accessorsArray.get(i*4+3);
            List<Object>accorsMin3=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors3.get("min")).size(); j++) {
                accorsMin3.add(((JSONArray) accors3.get("min")).get(j));
            }
            List<Object>accorsMax3=new ArrayList<>();
            for (int j = 0; j < ((JSONArray) accors3.get("max")).size(); j++) {
                accorsMax3.add(((JSONArray) accors3.get("max")).get(j));
            }

            Accessors accessors3=new Accessors(1,"VEC2",(Integer)accors3.get("componentType"),(Integer)accors3.get("count"),(Integer)accors3.get("byteOffset"),accorsMin3,accorsMax3);

            accessorsList.add(accessors);
            accessorsList.add(accessors1);
            accessorsList.add(accessors2);
            accessorsList.add(accessors3);
            gltfModel.setAccessors(accessorsList);
            //bufferViews属性
            JSONObject bufferViewsObj= (JSONObject) bufferViewerArray.get(i*2);
            JSONObject bufferViewsObj1= (JSONObject) bufferViewerArray.get(i*2+1);
//            BufferViews1 bufferViews1=new BufferViews1(0,0,12,34963);
            BufferViews1 bufferViews1=new BufferViews1();
//            BufferViews bufferViews=new BufferViews(0,12,128,34962,32);
            BufferViews bufferViews=new BufferViews();
            if(bufferViewsObj.containsKey("byteStride")){
//                5个属性
                bufferViews.setBuffer((int)bufferViewsObj.get("buffer"));
                bufferViews.setByteLength((int)bufferViewsObj.get("byteLength"));
                bufferViews.setByteOffset((int)bufferViewsObj.get("byteOffset"));
                bufferViews.setTarget((int)bufferViewsObj.get("target"));
                bufferViews.setByteStride((int)bufferViewsObj.get("byteStride"));
//                4个属性
                bufferViews1.setBuffer((int)bufferViewsObj1.get("buffer"));
                bufferViews1.setTarget((int)bufferViewsObj1.get("target"));
                bufferViews1.setByteOffset((int)bufferViewsObj1.get("byteOffset"));
                bufferViews1.setByteLength((int)bufferViewsObj1.get("byteLength"));
            }else {
                //                5个属性
                bufferViews.setBuffer((int)bufferViewsObj1.get("buffer"));
                bufferViews.setByteLength((int)bufferViewsObj1.get("byteLength"));
                bufferViews.setByteOffset((int)bufferViewsObj1.get("byteOffset"));
                bufferViews.setTarget((int)bufferViewsObj1.get("target"));
                bufferViews.setByteStride((int)bufferViewsObj1.get("byteStride"));
//                4个属性
                bufferViews1.setBuffer((int)bufferViewsObj.get("buffer"));
                bufferViews1.setTarget((int)bufferViewsObj.get("target"));
                bufferViews1.setByteOffset((int)bufferViewsObj.get("byteOffset"));
                bufferViews1.setByteLength((int)bufferViewsObj.get("byteLength"));

            }

            List<Object>bufferViewsList=new ArrayList<>();
            bufferViewsList.add(bufferViews1);
            bufferViewsList.add(bufferViews);
            gltfModel.setBufferViews(bufferViewsList);
            //buffers属性
            JSONObject bufferObject= (JSONObject) bufferArray.get(i);
            String bufUri=bufferObject.get("uri").toString();
            int byteLength= (int) bufferObject.get("byteLength");
            //"data:application/octet-stream;base64,AQACAAAAAgADAAAACHWHw/XqoMIIX4dBz9+RNQAAgL9WnxW1EACAPwAAgD/6b4DD8+qgwghfh0HP35E1AACAv1afFbUAAAA2AACAP/pvgMP06qDCoN/0Qc/fkTUAAIC/Vp8VtQAAADYAAAA0CHWHw/bqoMKg3/RBz9+RNQAAgL9WnxW1EACAPwAAADQ="
            Buffers buffers=new Buffers(bufUri,byteLength);
            List<Buffers>buffersList=new ArrayList<>();
            buffersList.add(buffers);
            gltfModel.setBuffers(buffersList);
            //images属性
            JSONObject imageObject= (JSONObject) imageArray.get(i);
            String imgUri= (String) imageObject.get("uri");
            Images images=new Images(imgUri);
            List<Images>imagesList=new ArrayList<>();
            imagesList.add(images);
            gltfModel.setImages(imagesList);
            //samplers属性
            Samplers samplers=new Samplers(9729,9729,10497,10497);
            List<Samplers>samplersList=new ArrayList<>();
            samplersList.add(samplers);
            gltfModel.setSamplers(samplersList);
            //textures属性
            Textures textures=new Textures(0,0);
            List<Textures>texturesList=new ArrayList<>();
            texturesList.add(textures);
            gltfModel.setTextures(texturesList);
            //materials属性
            BaseColorTexture baseColorTexture=new BaseColorTexture(0);
            PbrMetallicRoughness pbrMetallicRoughness=new PbrMetallicRoughness(baseColorTexture,new double[]{0.8,0.8,0.8,1},0,0.5);
            Materials materials=new Materials(pbrMetallicRoughness,new int[]{0,0,0},"OPAQUE",false,"chuanhukuang");
            List<Materials>materialsList=new ArrayList<>();
            materialsList.add(materials);
            gltfModel.setMaterials(materialsList);
            //创建文件
//            A5-1  写死
         String desPath= CreateModelFile("window"+i,"A5-1");
            //写入目标文件
         String gltfString = JSONObject.toJSONString(gltfModel);
         writeGltf(gltfString,desPath);

        }
     log.info("成功");




//        新建文件夹   返回文件路径
     String fileName="A5_10";
//     CreateModelFile();
//     写入.gltf
//     writeGltf(jobj,"E:\\filepath\\test\\1.gltf");
//        beanToJson();
    }
//    读取json文件
    public static String readJsonFile(String fileName) {
        FileReader fileReader = null;
        Reader reader = null;
        try {
             File jsonFile = new File(fileName);
//            File jsonFile = ResourceUtils.getFile("classpath:"+fileName);
            fileReader = new FileReader(jsonFile);
            reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            String jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
//            logger.error("读取文件报错", e);
            log.error("读取文件报错", e);
        } finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    //创建文件夹p
    public static String CreateModelFile(String fileName,String dirName)  {
//        String fileName="1.gltf";
        File testFile = new File("E:" + File.separator + "ZpGltf" + File.separator + dirName + File.separator + fileName+".gltf");
        File fileParent = testFile.getParentFile();//返回的是File类型,可以调用exsit()等方法
        String fileParentPath = testFile.getParent();//返回的是String类型
//        System.out.println("fileParent:" + fileParent);
        System.out.println("fileParentPath:" + fileParentPath);
        if (!fileParent.exists()) {
            fileParent.mkdirs();// 能创建多级目录
        }
        if (!testFile.exists())
            try {
                testFile.createNewFile();//有路径才能创建文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        System.out.println(testFile);
        return testFile.getAbsolutePath();
    }
    public static void writeGltf(String jsonString,String newPath){
        try
        {

            try {
                FileWriter file = new FileWriter(newPath);
                file.write(jsonString);
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
public static int getWindowNum(String fileName){
    String res=readJsonFile(fileName);
    Map jobj = JSON.parseObject(res);
    JSONArray nodesArray= (JSONArray) jobj.get("nodes");
    return nodesArray.size();
}
public static List<String> getWindowJson(String fileName){
     List<String> resJson=new ArrayList<>();
//    "json/A5_10—chuanghu.gltf"
    String res=readJsonFile(fileName);
    Map jobj = JSON.parseObject(res);
    JSONArray nodesArray= (JSONArray) jobj.get("nodes");
    JSONObject assetObject= (JSONObject) jobj.get("asset");
    JSONArray meshArray= (JSONArray) jobj.get("meshes");
    JSONArray bufferArray=(JSONArray) jobj.get("buffers");
    JSONArray imageArray= (JSONArray) jobj.get("images");
    JSONArray accessorsArray= (JSONArray) jobj.get("accessors");
    JSONArray bufferViewerArray= (JSONArray) jobj.get("bufferViews");
    //没遍历一次，写入文件一次 一条sql记录
    for (int i = 0; i < nodesArray.size(); i++) {
        GltfModel gltfModel=new GltfModel();
        //nodes属性
        JSONObject  nodeJson= (JSONObject) nodesArray.get(i);
        Nodes nodeObject=JSON.parseObject(nodeJson.toJSONString(),Nodes.class);
        nodeObject.setMesh(0);
        List<Nodes>nodesList=new ArrayList<>();
        nodesList.add(nodeObject);
        gltfModel.setNodes(nodesList);
        //asset属性
        Asset asset=JSON.parseObject(assetObject.toJSONString(),Asset.class);
        gltfModel.setAsset(asset);
        //scene属性
        int[]sceneNodes=new int[]{0};
        Scene scene=new Scene(sceneNodes);
        List<Scene>sceneList=new ArrayList<>();
        sceneList.add(scene);
        gltfModel.setScenes(sceneList);
        //meshes属性
        JSONObject meshJson= (JSONObject) meshArray.get(i);
        JSONArray primitivesArray= (JSONArray) meshJson.get("primitives");
        JSONObject primiviteJson= (JSONObject) primitivesArray.get(0);
        Primitive primitive=JSONObject.parseObject(primiviteJson.toJSONString(),Primitive.class);
        primitive.setIndices(0);
        Attributes attributes=new Attributes(1,2,3);
        primitive.setAttributes(attributes);
        String meshesName= (String) meshJson.get("name");
        List<Primitive>primitiveList=new ArrayList<>();
        primitiveList.add(primitive);
        Meshes meshes=new Meshes(meshesName, primitiveList);
        List<Meshes>meshesList=new ArrayList<>();
        meshesList.add(meshes);
        gltfModel.setMeshes(meshesList);
        //accessors属性
        List<Accessors>accessorsList=new ArrayList<>();
        JSONObject accors= (JSONObject) accessorsArray.get(i*4);
        List<Object>accorsMin=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors.get("min")).size(); j++) {
            accorsMin.add(((JSONArray) accors.get("min")).get(j));
        }
        List<Object>accorsMax=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors.get("max")).size(); j++) {
            accorsMax.add(((JSONArray) accors.get("max")).get(j));
        }

        Accessors accessors=new Accessors(0,"SCALAR", (Integer) accors.get("componentType"),(Integer)accors.get("count"), (Integer) accors.get("byteOffset"),accorsMin, accorsMax);

        JSONObject accors1= (JSONObject) accessorsArray.get(i*4+1);
        List<Object>accorsMin1=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors1.get("min")).size(); j++) {
            accorsMin1.add(((JSONArray) accors1.get("min")).get(j));
        }
        List<Object>accorsMax1=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors1.get("max")).size(); j++) {
            accorsMax1.add(((JSONArray) accors1.get("max")).get(j));
        }

        Accessors accessors1=new Accessors(1,"VEC3",(Integer)accors1.get("componentType"),(Integer)accors1.get("count"),(Integer)accors1.get("byteOffset"),accorsMin1,accorsMax1);

        JSONObject accors2= (JSONObject) accessorsArray.get(i*4+2);
        List<Object>accorsMin2=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors2.get("min")).size(); j++) {
            accorsMin2.add(((JSONArray) accors2.get("min")).get(j));
        }
        List<Object>accorsMax2=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors2.get("max")).size(); j++) {
            accorsMax2.add(((JSONArray) accors2.get("max")).get(j));
        }

        Accessors accessors2=new Accessors(1,"VEC3",(Integer)accors2.get("componentType"),(Integer)accors2.get("count"),(Integer)accors2.get("byteOffset"),accorsMin2,accorsMax2);

        JSONObject accors3= (JSONObject) accessorsArray.get(i*4+3);
        List<Object>accorsMin3=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors3.get("min")).size(); j++) {
            accorsMin3.add(((JSONArray) accors3.get("min")).get(j));
        }
        List<Object>accorsMax3=new ArrayList<>();
        for (int j = 0; j < ((JSONArray) accors3.get("max")).size(); j++) {
            accorsMax3.add(((JSONArray) accors3.get("max")).get(j));
        }

        Accessors accessors3=new Accessors(1,"VEC2",(Integer)accors3.get("componentType"),(Integer)accors3.get("count"),(Integer)accors3.get("byteOffset"),accorsMin3,accorsMax3);

        accessorsList.add(accessors);
        accessorsList.add(accessors1);
        accessorsList.add(accessors2);
        accessorsList.add(accessors3);
        gltfModel.setAccessors(accessorsList);
        //bufferViews属性
        JSONObject bufferViewsObj= (JSONObject) bufferViewerArray.get(i*2);
        JSONObject bufferViewsObj1= (JSONObject) bufferViewerArray.get(i*2+1);
//            BufferViews1 bufferViews1=new BufferViews1(0,0,12,34963);
        BufferViews1 bufferViews1=new BufferViews1();
//            BufferViews bufferViews=new BufferViews(0,12,128,34962,32);
        BufferViews bufferViews=new BufferViews();
        if(bufferViewsObj.containsKey("byteStride")){
//                5个属性
            bufferViews.setBuffer(0);
            bufferViews.setByteLength((int)bufferViewsObj.get("byteLength"));
            bufferViews.setByteOffset((int)bufferViewsObj.get("byteOffset"));
            bufferViews.setTarget((int)bufferViewsObj.get("target"));
            bufferViews.setByteStride((int)bufferViewsObj.get("byteStride"));
//                4个属性
            bufferViews1.setBuffer(0);
            bufferViews1.setTarget((int)bufferViewsObj1.get("target"));
            bufferViews1.setByteOffset((int)bufferViewsObj1.get("byteOffset"));
            bufferViews1.setByteLength((int)bufferViewsObj1.get("byteLength"));
        }else {
            //                5个属性
            bufferViews.setBuffer(0);
            bufferViews.setByteLength((int)bufferViewsObj1.get("byteLength"));
            bufferViews.setByteOffset((int)bufferViewsObj1.get("byteOffset"));
            bufferViews.setTarget((int)bufferViewsObj1.get("target"));
            bufferViews.setByteStride((int)bufferViewsObj1.get("byteStride"));
//                4个属性
            bufferViews1.setBuffer(0);
            bufferViews1.setTarget((int)bufferViewsObj.get("target"));
            bufferViews1.setByteOffset((int)bufferViewsObj.get("byteOffset"));
            bufferViews1.setByteLength((int)bufferViewsObj.get("byteLength"));

        }

        List<Object>bufferViewsList=new ArrayList<>();
        bufferViewsList.add(bufferViews1);
        bufferViewsList.add(bufferViews);
        gltfModel.setBufferViews(bufferViewsList);
        //buffers属性
        JSONObject bufferObject= (JSONObject) bufferArray.get(i);
        String bufUri=bufferObject.get("uri").toString();
        int byteLength= (int) bufferObject.get("byteLength");
        //"data:application/octet-stream;base64,AQACAAAAAgADAAAACHWHw/XqoMIIX4dBz9+RNQAAgL9WnxW1EACAPwAAgD/6b4DD8+qgwghfh0HP35E1AACAv1afFbUAAAA2AACAP/pvgMP06qDCoN/0Qc/fkTUAAIC/Vp8VtQAAADYAAAA0CHWHw/bqoMKg3/RBz9+RNQAAgL9WnxW1EACAPwAAADQ="
        Buffers buffers=new Buffers(bufUri,byteLength);
        List<Buffers>buffersList=new ArrayList<>();
        buffersList.add(buffers);
        gltfModel.setBuffers(buffersList);
        //images属性
        JSONObject imageObject= (JSONObject) imageArray.get(0);
        String imgUri= (String) imageObject.get("uri");
        Images images=new Images(imgUri);
        List<Images>imagesList=new ArrayList<>();
        imagesList.add(images);
        gltfModel.setImages(imagesList);
        //samplers属性
        Samplers samplers=new Samplers(9729,9729,10497,10497);
        List<Samplers>samplersList=new ArrayList<>();
        samplersList.add(samplers);
        gltfModel.setSamplers(samplersList);
        //textures属性
        Textures textures=new Textures(0,0);
        List<Textures>texturesList=new ArrayList<>();
        texturesList.add(textures);
        gltfModel.setTextures(texturesList);
        //materials属性
        BaseColorTexture baseColorTexture=new BaseColorTexture(0);
        PbrMetallicRoughness pbrMetallicRoughness=new PbrMetallicRoughness(baseColorTexture,new double[]{0.8,0.8,0.8,1},0,0.5);
        Materials materials=new Materials(pbrMetallicRoughness,new int[]{0,0,0},"OPAQUE",false,"chuanhukuang");
        List<Materials>materialsList=new ArrayList<>();
        materialsList.add(materials);
        gltfModel.setMaterials(materialsList);

        String gltfString = JSONObject.toJSONString(gltfModel);
        resJson.add(gltfString);

    }
    return resJson;
}
public static String test(){
        return "333333333333";
}

}
